import React, {useEffect, useState} from 'react';
import {connect} from "react-redux";
import * as Icon from "react-feather"
import ContactForm from "./ContactForm";
import {setFieldData, setFieldIdData} from "../../../redux/actions/helper";
import {DeleteContact, getContacts, getTypes} from "../../../redux/actions/contacts";
import FullSpinnerDimming from "../../../components/@vuexy/spinner/Full-spinner-dimming";
import {Card, CardHeader, CardBody, Button, CustomInput} from "reactstrap";
import {SET_CONTACT_FIELD} from "../../../redux/constants/contacts";
import '../../../assets/scss/pages/contacts.scss';
import {ContextLayout} from "../../../utility/context/Layout";
import {AgGridReact} from "ag-grid-react";
import "../../../assets/scss/plugins/tables/_agGridStyleOverride.scss"
import {Trash} from "react-feather";
import Filter from "./Filter";

const Contacts = (props) => {
  const {params, reqParams, contacts, spinner, types} = props
  const {setFieldData, getTypes, getContacts, DeleteContact} = props

  const getContactByTypes = (type) => {
    return contacts.filter((contact) => {
      return contact.type.id === type.id
    }).map((contact) => {
      let data = {
        id: contact.id,
        name: contact.name,
        phone: contact.phone,
        email: contact.email,
        created_at: contact.created_at,
        updated_at: contact.updated_at,
      }
      contact.data.map(contact => {
        data[contact.key] = contact.value
      })
      return data
    })
  }

  const getColumnDefsByType = (type) => {
    let data = [
      {headerName: 'Имя Фамилия', field: 'name'},
      {headerName: 'Email', field: 'email'},
      {headerName: 'Телефон', field: 'phone'},
    ]
    data = data.concat(JSON.parse(type.data).map(type => {
      switch (type.type) {
        case 'boolean':
          return {
            headerName: type.name,
            field: type.key,
            cellRendererFramework: params => {
              return params.value === true ? 'Да' : 'Нет'
            }
          }
        case 'link':
          return {
            headerName: type.name,
            field: type.key,
            cellRendererFramework: params => {
              return params.value ? <a href={params.value}>Перейти</a> : ''
            }
          }
        default :
          return {
            headerName: type.name,
            field: type.key,
          }
      }
    }))
    data.push({headerName: 'Редактировать', field: 'edit', cellRendererFramework: parameters => {
        return <div>
          <Button.Ripple className="p-1" color="flat-primary"
                         onClick={()=>setFieldData(SET_CONTACT_FIELD, 'params', {
                           ...parameters,
                           contact_id: parameters.data.id,
                           isOpenModal: true
                         })}
          >
            <Icon.Edit2 size={18}/>
          </Button.Ripple>
          <Button.Ripple className="p-1" color="flat-danger"
                         onClick={()=>DeleteContact(parameters.data.id, reqParams, params)}
          >
            <Trash size={18}/>
          </Button.Ripple>
        </div>
      }})

    return data
  }

  useEffect(() => {
    getTypes()
  }, [])

  useEffect(() => {
    if (!params.isOpenModal)
      getContacts(reqParams)
  }, [params.isOpenModal])

  const settings = {
    defaultColDef: {
      sortable: true,
      cellStyle: {border: 'none'},
    },
    rowStyle: {borderColor: 'transparent', borderWidth: '4px', cursor: 'pointer'},
    rowSelection: 'single'
  }


  const onRowDoubleClicked = (gridApi) => {
    let selectedRows = gridApi.api.getSelectedRows();
    console.log(selectedRows)
    setFieldData(SET_CONTACT_FIELD, 'params', {
      ...params,
      contact_id: selectedRows[0].id,
      isOpenModal: true
    })
  };

  return (
    <React.Fragment>

      {spinner.includes('contacts') && <FullSpinnerDimming/>}

      <ContactForm />


      <Card className="px-2">
        <CardHeader className={'d-flex justify-content-between'}>
          <h1>Контакты</h1>
          <Button.Ripple onClick={() => setFieldData(SET_CONTACT_FIELD, 'params', {
            ...params,
            contact_id: null,
            isOpenModal: true
          })} color="danger" className="btn-uppercase">
            Добавить контакт
          </Button.Ripple>
        </CardHeader>
        <CardBody className="pt-2">
          <Filter />
        </CardBody>
      </Card>


      {
        types.filter(type=>{
          if(reqParams.type === -1) return true
          else return reqParams.type === type.id
        }).map(type => {
          return <Card className="px-2" key={type.id}>
            <CardHeader>
              <h3>{type.name}</h3>
            </CardHeader>
            <CardBody className="pt-2">
              <div className="ag-theme-material ag-grid-table">
                <ContextLayout.Consumer>
                  {context => (
                    <AgGridReact
                      defaultColDef={settings.defaultColDef}
                      columnDefs={getColumnDefsByType(type)}
                      rowData={getContactByTypes(type)}
                      rowStyle={settings.rowStyle}
                      colResizeDefault={"shift"}
                      animateRows={true}
                      onRowDoubleClicked={onRowDoubleClicked.bind(this)}
                      pagination={false}
                      rowSelection={settings.rowSelection}
                    />
                  )}
                </ContextLayout.Consumer>
              </div>
            </CardBody>
          </Card>
        })
      }
    </React.Fragment>
  )
}

const mapStateToProps = state => ({
  contact: state.contacts.contact,
  params: state.contacts.params,
  types: state.contacts.types,
  reqParams: state.contacts.reqParams,
  contacts: state.contacts.contacts,
  spinner: state.helper.spinner,
})

export default connect(mapStateToProps, {
  setFieldData, setFieldIdData, getContacts, getTypes, DeleteContact
})(Contacts);
